# select cells with path to scc
function ancestors(G::SimpleDiGraph{Int64}, src)
    reverse!(G)
    a = Vector{Int64}()
    @inbounds for (v, d) in enumerate(gdistances(G, src))
        if d < typemax(Int64)
            push!(a, v)
        end
    end
    reverse!(G)
    return a
end

# select non-leaving cells
function select_nonleaving_cells(G::SimpleDiGraph{Int64})
	scc = strongly_connected_components(G)
	idx = 0
    len = 0
    @inbounds for i in 1:length(scc)
        l = length(scc[i])
        l > len && (idx = i; len=l) 
    end
    da = ancestors(G, scc[idx])
    return union(scc[idx],da)
end

# create RTree
function create_rtree(Rk::Vector{Vector{Int}}, ds::DiscreteSpace)
    dim = ds.dim
    dX = ds.dX
    rtree = RTree{Float64,dim}(Int)

    @inbounds for (id,bxi) in enumerate(Rk)
        bx = [dX[j][bxi[j]] for j in 1:dim]
        lb = Tuple(bx[j].lo for j in 1:dim)
        ub = Tuple(bx[j].hi for j in 1:dim)
        rec = Rect(lb,ub)
        insert!(rtree,rec,id)
    end
    return rtree
end

# create cells to visualization and processing
function create_boxes(Rk::Vector{Vector{Int}},ds::DiscreteSpace)
    boxes = Vector{typeof(Hyperrectangle(low=zeros(ds.dim),high=zeros(ds.dim)))}()
    dim = ds.dim
    dX = ds.dX
    @inbounds for bxi in Rk
        bx = [dX[j][bxi[j]] for j in 1:dim]
        lb = [bx[j].lo for j in 1:dim]
        ub = [bx[j].hi for j in 1:dim]
        push!(boxes, Hyperrectangle(low=lb,high=ub))
    end
    return boxes
end

# find all incoming neighbors of the leaving cells
function all_inneighbors(G, lc)
    V = []

    for i in lc
        push!(V,inneighbors(G,i))
    end
    
    return V

end